package com.atguigu.tingshu.order.delay;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * RedisDelayHandler 延迟队列 处理任务
 *
 * @author Petrichor
 * @version 2024/01/08 18:03
 **/
@Component
@EnableScheduling
@Slf4j
public class RedisDelayHandler {
    private final RedissonClient redissonClient;
    private final OrderInfoService orderInfoService;
    @Autowired
    public RedisDelayHandler(RedissonClient redissonClient, OrderInfoService orderInfoService) {
        this.redissonClient = redissonClient;
        this.orderInfoService = orderInfoService;
    }

    /**
     * @description: 每秒处理一次
     * @author Petrichor
     * @date 2024/1/8 18:04
     * @param
     * @return
    **/
    @Scheduled(cron = "0/1 * * * * ? ")
    public void delayMsgConsumer() {
        // 使用分布式锁防止任务重复执行
        RLock rLock = redissonClient.getLock("lock");
        // 尝试获取锁
        boolean tryLock = rLock.tryLock();
        if (tryLock){
            // 获取到分布式锁以后执行关单业务逻辑代码
            // 获取阻塞队列
            RBlockingDeque<Object> orderCancelBlockingDeque = redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
            try {
                // 获取Redis中的阻塞队列
                RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
                Object take = blockingDeque.take();
                orderInfoService.orderCancel(take.toString()) ;

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                // 任务执行完毕以后，释放分布式锁
                rLock.unlock();
            }
        }
    }
}


